<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="referrer" content="origin-when-cross-origin">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>报修服务</title>
    <link href="../../css/common.css" rel="stylesheet">
    <link href="../../css/form.css" rel="stylesheet">
    <link href="../../plugin/layui-v2.9.0/css/layui.css" rel="stylesheet">
</head>

<body>
    <div class="form-content">
        <div class="top-header">
            <div class="content">
                <span class="server-name">
                    申请报修服务
                </span> 
            </div>
        </div>
        <div class="form-box">
            <div class="content">
                <!-- 表单 -->
                <form class="layui-form">
                    <!-- 报修人 -->
                    <div class="layui-form-item">
                        <label class="layui-form-label">
                            <span class="required">*</span> 报修人
                        </label>
                        <div class="layui-inline">
                            <input type="text" id="rep_wo_repairbodyname" lay-verify="required" placeholder="请输入"
                                autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <!-- 联系电话 -->
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 联系电话</label>
                        <div class="layui-inline">
                            <input type="text" id="rep_wo_phone" lay-verify="required|phone" placeholder="请输入手机号"
                                autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <!-- 报修区域 -->
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 报修区域</label>
                        <div class="layui-input-inline">
                            <button class="layui-btn layui-btn-primary" id="areaId">
                                <span id="selectedArea">请选择报修区域</span>
                                <i class="layui-icon layui-icon-down layui-font-12"></i>
                            </button>
                        </div>
                    </div>
                    <!-- 报修项目 -->
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 报修项目</label>
                        <div class="layui-input-inline">
                            <button class="layui-btn layui-btn-primary" id="repi_id">
                                <span id="selectedItem">请选择报修项目</span>
                                <i class="layui-icon layui-icon-down layui-font-12"></i>
                            </button> 
                        </div>
                    </div>
                    <!-- 详细地址 -->
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span>详细地址</label>
                        <div class="layui-input-block">
                            <input type="text" id="rep_wo_detailed_address" lay-verify="required" placeholder="请输入详细地址"
                                autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <!-- 故障描述 -->
                    <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">故障描述</label>
                        <div class="layui-input-block">
                            <textarea id="rep_wo_fault_description" placeholder="详细描述故障"
                                class="layui-textarea"></textarea>
                        </div>
                    </div>
                    <!-- 故障图片 -->
                    <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">故障图片</label>
                        <div class="layui-input-block">
                            <div class="layui-upload-drag" style="display: block;" id="upload_btn">
                                <i class="layui-icon layui-icon-upload"></i>
                                <div><span class="link">点击上传图片</span> 或将图片拖拽到此处，图片大小不超过 10M</div>
                            </div>
                        </div>
                        <div class="layui-input-block">
                            <div class="layui-upload-list" id="upload_preview_list"></div>
                        </div>
                    </div>
                    <!-- 预约时间 -->
                    <div class="layui-inline">
                        <label class="layui-form-label">预约时间</label>
                        <div class="layui-input-inline layui-input-wrap">
                            <div class="layui-input-prefix">
                                <i class="layui-icon layui-icon-date"></i>
                            </div>
                            <input type="text" class="layui-input" id="appointDate" placeholder="请选择预约时间">
                        </div>
                    </div>
                    <!-- 是否允许无人时维修 -->
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 是否允许无人时维修</label>
                        <div class="layui-input-block">
                            <input type="radio" name="rep_wo_will_no_body_done" value="1" title="是" checked>
                            <input type="radio" name="rep_wo_will_no_body_done" value="2" title="否">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block to-right">
                            <button type="button"
                                class="to_back layui-btn layui-btn-primary layui-border-purple">返回</button>
                            <button type="button" class="saveForm layui-btn">提交</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script src="../../plugin/layui-v2.9.0/layui.js"></script>
    <script src="../../plugin/jquery-2.0.0.min.js"></script>
    <script src="../../plugin/tool.js"></script>
    <script src="../../js/config.js"></script>
    <script src="../../api.js"></script>
    <script src="../../mock/data.js"></script>
    <script>
        $(function () {
            API.addClickTimes("报修服务");
        })
        var form, upload, laydate, element, dropdown;
        layui.use(function () {
            form = layui.form;
            upload = layui.upload;
            laydate = layui.laydate;
            element = layui.element;
            dropdown = layui.dropdown; 
            FORM.initPage();
        });
        var FORM = {
            pageDict: null,  
            selectArea:null,
            selectItem:null,
            system_rep_wo_imgs: [],
            initPage: function () {
                upload.render({
                    elem: '#upload_btn',
                    multiple: true,
                    size: 10240,
                    acceptMime: 'image/jpeg, image/png',
                    url: API.baseURL + API.uploadUrl,
                    text: { // 自定义提示文本
                        "data-format-error": "数据格式错误!", // 数据格式错误的提示
                        "check-error": "文件格式校验失败!", // 文件格式校验失败的提示
                        "error": "上传失败！", // 上传失败的提示
                        "limit-number": null, // 限制 number 属性的提示。若设置，需为函数写法
                        "limit-size": function () {
                            return "上传文件大小不能大于10M!";
                        },
                        "cross-domain": "", // IE 下跨域的提示
                    },
                    before: function (obj) {
                        obj.preview(function (index, file, result) {
                            if (file.type == "image/jpeg" || file.type == "image/png") {
                                var html = '<div class="img_list"><img src="' + result + '" alt="' + file.name + '"><a href="Javascript:void(0)" alt="' + file.name + '"><i class="layui-icon layui-icon-error"></i></a></div>';
                                $('#upload_preview_list').append(html)
                            }
                        });
                    },
                    done: function (res) {
                        layer.msg('上传成功');
                        // layer.close(layer.index);   
                        //console.log(res);
                        FORM.system_rep_wo_imgs.push(res);
                        // $('#upload_preview_list').append('<img src="' + result + '" alt="' + file.name + '" style="width: 90px; height: 90px;">')
                        // //console.log(res)
                    }
                });
                laydate.render({
                    elem: '#appointDate',
                    type: 'datetime',
                    min: new Date().format("yyyy-MM-dd")
                });

                $(".to_back").click(function () {
                    window.location.href = "../../index.html";
                });
                $("#upload_preview_list").delegate("a", "click", function () {
                    $(this).parents("div.img_list").remove();
                    var alt = $(this).attr("alt");
                    var index = -1;
                    for (var i = 0; i < FORM.system_rep_wo_imgs.length; i++) {
                        if (FORM.system_rep_wo_imgs[i].showname == alt) {
                            index = i;
                            break;
                        }
                    }
                    if (index >= 0) {
                        FORM.system_rep_wo_imgs.splice(i, 1);
                    }
                });
                $(".saveForm").click(function () {
                    FORM.saveForm();
                });
                var name = localStorage.getItem("os_u_full_name");
                var phone = localStorage.getItem("os_u_phone");
                if (name) {
                    $("#rep_wo_repairbodyname").val(name);
                }
                if (phone) {
                    $("#rep_wo_phone").val(phone);
                }

                API.getRepairPageDict(function (json) {
                    //console.log(json);
                    if (json.code != "0") {
                        layer.alert(json.codemessage);
                        return;
                    } else {
                        FORM.pageDict = json;
                        FORM.setQu1Data();
                    }
                }); 
                dropdown.render({
                    elem: '#repi_id'
                    , id: 'repi_id'
                    , data: []
                    , click: function (obj) {
                        $("#selectedItem").html(obj.pname);
                        FORM.selectItem = obj;
                        //console.log(obj);
                    }
                }); 
            },
            setQu1Data: function () { 
                var quData = [];
                FORM.pageDict.repair_area.forEach(item => {
                    if (item.rep_a_isusing == "1" && item.rep_a_fatherid == "") {
                        var pids = [];
                        pids.push(item.rep_a_id);
                        quData.push({
                            title: item.rep_a_name,
                            pname:item.rep_a_name,
                            id:item.rep_a_id,
                            pids:pids,
                            child:FORM.getAreaChild(item.rep_a_id,item.rep_a_name,pids)
                        });
                    }
                });
                dropdown.render({
                    elem: '#areaId'
                    , id: 'areaId'
                    , data: quData
                    , click: function (obj) {
                        $("#selectedArea").html(obj.pname);
                        FORM.selectArea = obj;
                        //console.log("selectArea",FORM.selectArea);
                        FORM.selectItem=null;
                        $("#selectedItem").html("请选择报修项目");
                        FORM.setRepairItem();
                    }
                }); 
                layui.form.render($('#areaId'));
            },
            getAreaChild:function(rep_a_id,pname,pids){
                var quData = [];
                FORM.pageDict.repair_area.forEach(item => {
                    if (item.rep_a_isusing == "1" && item.rep_a_fatherid == rep_a_id) {
                        var thisPname =  pname?pname+"/"+item.rep_a_name:item.rep_a_name;
                        var thisPids = [].concat(pids);
                        thisPids.push(item.rep_a_id);
                        quData.push({
                            title: item.rep_a_name,
                            id:item.rep_a_id,
                            pname:thisPname,
                            pids:thisPids,
                            child:FORM.getAreaChild(item.rep_a_id,thisPname,thisPids)
                        });
                    }
                });
                return quData;
            },
            allSeleteIds:[],
            setRepairItem: function () {   
                if(!FORM.selectArea){
                    return;
                }
                //---------------------------------
                var aItems = [];
                FORM.pageDict.repair_area_unit_set.forEach(item => {
                    if (item.rep_aus_isusing != "1") {
                        return true;
                    }
                    //判断当前报修项目是否配置报修项目
                    var index = FORM.selectArea.pids.findIndex(areaId=>areaId == item.rep_a_id);
                    if(index<0){
                        return true;
                    }
                    //当前报修项目符合条件时，需要判断是否已添加
                    var index = aItems.findIndex(pitem => pitem.rep_i_id == item.rep_i_id);
                    if (index < 0) {
                        //未添加时，则采用
                        aItems.push({
                            rep_i_id:item.rep_i_id, //项目id
                            rep_ug_id:item.rep_ug_id,//单位分组id
                            rep_aus_sflx:item.rep_aus_sflx//收费类型
                        });
                    } 
                });
                //为当前选择的报修项目增加子集
                //console.log("aItems",aItems);
                //---------------------------------
                var allItemTrees=[];//树形结构，存储所有已被选择的报修项目
                FORM.allSeleteIds=[];//列表结构，存储所有已被选择的报修项目id
                //先添加1级
                aItems.forEach(aItem=>{ 
                    FORM.setItemInfo(allItemTrees,aItem,aItems,true);
                });
                aItems.forEach(aItem=>{
                    //如果在循环中，数据已被添加，则不再添加
                    if(FORM.allSeleteIds.findIndex(id=> id==aItem.rep_i_id)>=0){
                        return true;
                    }
                    FORM.setItemInfo(allItemTrees,aItem,aItems,false);
                });
                //console.log("aItems",allItemTrees);
                dropdown.reloadData('repi_id',{
                     data: allItemTrees
                }); 
                layui.form.render($('#repi_id'));
            },
            setItemInfo:function(allItemTrees,aItem,aItems,isparent){
                 //选择项目对应的数据
                var itemNode = FORM.pageDict.repair_item.find(ri=>ri.rep_i_isusing=="1" && ri.rep_i_id == aItem.rep_i_id);
                if(!itemNode){
                    return true;
                } 
                if(isparent && itemNode.rep_i_fatherid!=""){
                    return true;
                }
                var child = FORM.getChildItem(aItem.rep_i_id,aItem,aItems,itemNode.rep_i_name);
                allItemTrees.push({
                    id: itemNode.rep_i_id,
                    title:itemNode.rep_i_name,
                    rep_ug_id:aItem.rep_ug_id,//单位分组id
                    rep_aus_sflx:aItem.rep_aus_sflx,//收费类型
                    pname:itemNode.rep_i_name,
                    child
                });
                //符合条件，则将数据存入选择的id中
                FORM.allSeleteIds.push(aItem.rep_i_id);
            },
            getChildItem:function(rep_i_id,thisAitem,aItems,pname){
                var itemData = [];
                FORM.pageDict.repair_item.forEach(rp_item => {
                    if (rp_item.rep_i_isusing == "1" && rp_item.rep_i_fatherid == rep_i_id) {
                        //判断当前维修项目 收费情况是否在选择的对象中
                        var thisAitem_ =  aItems.find(a_item=> a_item.rep_i_id = rp_item.rep_i_id);
                        if(thisAitem_){
                            thisAitem = thisAitem_;
                        }
                        var pname_ = pname?(pname+"/"+rp_item.rep_i_name):rp_item.rep_i_name;
                        var child = FORM.getChildItem(rp_item.rep_i_id,thisAitem,aItems,pname_);
                        itemData.push({
                            id: rp_item.rep_i_id,
                            title:rp_item.rep_i_name,
                            rep_ug_id:thisAitem.rep_ug_id,//单位分组id
                            rep_aus_sflx:thisAitem.rep_aus_sflx,//收费类型
                            pname:pname_,
                            child
                        });
                        //符合条件，则将数据存入选择的id中
                        FORM.allSeleteIds.push(rp_item.rep_i_id);
                    }
                });
                return itemData;
            },
           
            saveForm: function () {
                var appointDate = $("#appointDate").val();
                var rep_wo_will_is, rep_wo_will_time1, rep_wo_will_time2;
                if (appointDate == "") {
                    rep_wo_will_is = "0";
                } else {
                    rep_wo_will_is = "1";
                    rep_wo_will_time1 = appointDate.split(" ")[0]; //预约维修的日期部分，例如“2023-10-10”
                    rep_wo_will_time2 = appointDate.split(" ")[1]; //预约维修的时间部分，例如“17:30”
                }
                var rep_a_id = "";//选择的“维修区域id” 
                var rep_a_name =  "";//选择的“区域名字”，
                var rep_a_nameall =  "";//选择的“区域名字全称”，例如：长安校区 / 学生生活区 / 2号楼
                if(FORM.selectArea){
                    rep_a_id = FORM.selectArea.id;
                    rep_a_name = FORM.selectArea.title;
                    rep_a_nameall = FORM.selectArea.pname;
                }
                

                var rep_i_name = "";  //选择的“维修项目名”
                var rep_i_id = ""; //选择的“项目id”
                var rep_i_nameall = "";  //选择的“项目名字全称”，例如：水 / 上下水管类
                var rep_wo_charge_type = ""; //收费类型(收费;免费)
                var rep_ug_id = ""; //维修单位分组id

                if(FORM.selectItem){
                    rep_i_name = FORM.selectItem.title; 
                    rep_i_id = FORM.selectItem.id;
                    rep_i_nameall = FORM.selectItem.pname;
                    rep_wo_charge_type = FORM.selectItem.rep_aus_sflx;
                    rep_ug_id = FORM.selectItem.rep_ug_id;
                }

                var formInfo = {
                    rep_wo_sizetype: "普通维修",
                    rep_wo_urgent: "普通",
                    rep_wo_ispublic: "0",
                    rep_wo_identity_type: "学生",
                    rep_wo_xh_gh: localStorage.getItem("os_u_name"),
                    rep_wo_source: "自主报修",
                    rep_wo_sourcetype: "PC端",

                    rep_wo_detailed_address: $("#rep_wo_detailed_address").val(),
                    rep_wo_fault_description: $("#rep_wo_fault_description").val(),
                    rep_wo_repairbodyname: $("#rep_wo_repairbodyname").val(),
                    rep_wo_phone: $("#rep_wo_phone").val(),
                    rep_wo_will_time1,
                    rep_wo_will_time2,
                    rep_wo_will_is,
                    rep_wo_will_no_body_done: $("input[name=rep_wo_will_no_body_done]:checked").val(),
                    rep_a_name,
                    rep_a_id,
                    rep_a_nameall,
                    rep_i_id,
                    rep_i_name,
                    rep_i_nameall,
                    rep_wo_charge_type,
                    rep_wo_imgs: JSON.stringify(FORM.system_rep_wo_imgs),//故障图片
                    rep_ug_id: rep_ug_id
                };
                //console.log(formInfo); 
                var has_error = false;
                if (!formInfo.rep_wo_repairbodyname) {
                    layer.tips("报修人不能为空！",$("#rep_wo_repairbodyname"),{tipsMore: true,tips:[1, 'red']});
                    has_error = true;
                }
                if (!formInfo.rep_wo_phone) {
                    layer.tips("联系电话不能为空！",$("#rep_wo_phone"),{tipsMore: true,tips:[1, 'red']});
                    has_error = true;
                }
                if (!formInfo.rep_wo_detailed_address) {
                    layer.tips("详细地址不能为空！",$("#rep_wo_detailed_address"),{tipsMore: true,tips:[1, 'red']});
                    has_error = true;
                }
                if (!formInfo.rep_a_id) { 
                    layer.tips("报修区域不能为空！",$("#selectedArea"),{tipsMore: true,tips:[1, 'red']});
                    has_error = true;
                }
                if (!formInfo.rep_i_id) {
                    layer.tips("报修项目不能为空！",$("#selectedItem"),{tipsMore: true,tips:[1, 'red']});
                    has_error = true;
                }
                //console.log(formInfo);
                if(has_error){
                    layer.msg("请填写完毕后提交！")
                    return;
                } 
                layer.load();
                API.submitBaox(formInfo, function (json) {
                    if (json.code != "0") {
                        layer.close(layer.index);
                        layer.alert(json.codemessage);
                    } else {
                        layer.msg(json.codemessage);
                        setTimeout(function () {
                            window.location.href = "./list.html";
                        }, 1000);
                    }
                })
            }, 
        } 
    </script>
</body>

</html>